package com.xzcs.service.blog.friendlink;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xzcs.mapper.blog.friendlink.FriendlinkMapper;
import com.xzcs.mapper.sequence.SequenceMapper;
import com.xzcs.service.BaseService;
import com.xzcs.util.common.StringUtils;
import com.xzcs.util.web.RequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 
 * @author changs
 * @createDate 2018-03-30 16:07:18
 */
@Service
public class FriendlinkService extends BaseService {
	@Autowired
	private FriendlinkMapper friendlinkMapper;
	@Autowired
    private SequenceMapper sequenceMapper;
	
	public PageInfo<Map<String, Object>> findFriendlinks(HttpServletRequest request){
        String pageNum = RequestUtils.getValue(request, "page");//页数
        String pageSize = RequestUtils.getValue(request, "rows");//每页条数
        pageNum = pageNum.equals("") ? "1" : pageNum;
        pageSize = pageSize.equals("") ? getDefaultPageSize() : pageSize;
        Map<String, Object> params = RequestUtils.getRequestMap(request);
        PageHelper.startPage(StringUtils.toInt(pageNum), StringUtils.toInt(pageSize));
        List<Map<String, Object>> list = friendlinkMapper.findFriendlinks(params);
        PageInfo<Map<String, Object>> page = new PageInfo<Map<String, Object>>(list);
        return page;
    }

    public Map<String, Object> findFriendlink(HttpServletRequest request){
        String id = RequestUtils.getValue(request, "id");
        return friendlinkMapper.findFriendlink(id);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void saveFriendlink(HttpServletRequest request){
        Map<String, Object> user = this.getUser(request);
        String method = RequestUtils.getValue(request, "method");
        String id = RequestUtils.getValue(request, "id");
        Map<String, Object> params = RequestUtils.getRequestMap(request);
        params.put("userId", StringUtils.get(user, "user_id"));
        if (method.equals("create")) {
            id = sequenceMapper.getSequenceValue("seq_common_id")+"";
            params.put("id", id);
            friendlinkMapper.insertFriendlink(params);
        } else {
            params.put("id", id);
            friendlinkMapper.updateFriendlink(params);
        }
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void deleteFriendlink(HttpServletRequest request){
        String id = RequestUtils.getValue(request, "id");
        friendlinkMapper.deleteFriendlink(id);
    }
}
